#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:zhangcong
# Email:zc_92@sina.com

from django.shortcuts import render, redirect

# Create your views here.

from django.http import JsonResponse

from web.views_dir import pub

from web import models
from web.forms.userprofile import userprofileForms, userprofileForms_update
from web.forms.client_info import clientinfoForms, clientinfoForms_update


@pub.is_login
def userprofile(request):
    user_id = request.session['user_id']

    if "type" in request.GET and request.GET.get('type') == "ajax_json":

        department = models.UserProfile.objects.get(id=user_id).department
        if not department:
            userprofile_obj = models.UserProfile.objects.all()
        else:
            userprofile_obj = models.UserProfile.objects.filter(department_id=department.id)

        length = request.GET.get('length')  # 每页显示的数量
        start = request.GET.get('start')  # 第几页
        column_list = ['id', 'number', 'name', 'department__name', 'sex', 'phone', 'status']

        data_objs = pub.combining_data(userprofile_obj, request, column_list)

        line_count = data_objs.count()  # 过滤出来的数量
        data_objs = pub.paging(data_objs, start, length)  # 进行分页

        result_data = {
            'recordsFiltered': line_count,
            'data': []
        }
        for index, obj in enumerate(data_objs, start=1):

            sex = ""
            status = ""

            for s in obj.sex_choices:
                if obj.sex == s[0]:
                    sex = s[1]

            for s in obj.status_choices:
                if obj.status == s[0]:
                    status = s[1]

            if obj.department:
                department_name = obj.department.name
            else:
                department_name = None

            data = {
                'number': index,
                'name': obj.name,
                'department_name': department_name,
                'sex': sex,
                'phone': obj.phone,
                'status': status,
                'id': obj.id,
            }
            result_data['data'].append(data)
        return JsonResponse(result_data)

    if "_pjax" in request.GET:
        return render(request, 'webadmin/userprofile_pjax.html', locals())
    return render(request, 'webadmin/userprofile.html', locals())


@pub.is_login
def userprofile_oper(request, oper_type, user_id):
    user_id = request.session['user_id']
    response = pub.BaseResponse()

    if request.method == "POST":
        if oper_type == "create":
            form_obj = userprofileForms(request.POST)
            if form_obj.is_valid():
                password = pub.str_encrypt('123')
                models.UserProfile.objects.create(
                    name=form_obj.cleaned_data['name'],
                    phone=form_obj.cleaned_data['phone'],
                    sex=form_obj.cleaned_data['sex'],
                    password=password,
                    department=models.Department.objects.get(id=models.UserProfile.objects.get(id=user_id).department.id)
                )
                response.status = True
                response.message = "员工 {name} 添加成功!".format(name=form_obj.cleaned_data['name'])

            else:
                response.status = False
                response.message = form_obj.errors[list(form_obj.errors.keys())[0]]

        elif oper_type == "update":
            form_obj = userprofileForms_update(request.POST)
            if form_obj.is_valid():
                user_profile_obj = models.UserProfile.objects.filter(id=form_obj.cleaned_data['id'])
                user_profile_obj.update(
                    name=form_obj.cleaned_data['name'],
                    phone=form_obj.cleaned_data['phone'],
                    sex=form_obj.cleaned_data['sex'],
                )

                response.status = True
                response.message = "员工 {name} 修改成功!".format(name=form_obj.cleaned_data['name'])

            else:
                response.status = False
                response.message = form_obj.errors[list(form_obj.errors.keys())[0]]

        elif oper_type == "delete":
            user_profile_obj = models.UserProfile.objects.filter(id=user_id).delete()
            response.status = True
            response.message = "员工删除成功"

        elif oper_type == "set_departure":
            user_profile_obj = models.UserProfile.objects.get(id=user_id)
            user_profile_obj.status = 3
            user_profile_obj.save()

            response.status = True
            response.message = "设置成功"

        elif oper_type == "set_induction":
            user_profile_obj = models.UserProfile.objects.get(id=user_id)
            user_profile_obj.status = 2
            user_profile_obj.save()

            response.status = True
            response.message = "设置成功"

        return JsonResponse(response.__dict__)
    else:
        if oper_type == "create":
            return render(request, 'webadmin/userprofile_modal_create.html', locals())

        elif oper_type == "select":
            user_profile_obj = models.UserProfile.objects.get(id=user_id)
            return render(request, 'webadmin/userprofile_modal_select.html', locals())

        elif oper_type == "update":
            user_profile_obj = models.UserProfile.objects.get(id=user_id)
            return render(request, 'webadmin/userprofile_modal_update.html', locals())

        elif oper_type == "delete":
            user_profile_obj = models.UserProfile.objects.get(id=user_id)
            return render(request, 'webadmin/userprofile_modal_delete.html', locals())

        # 设置为离职
        elif oper_type == "set_departure":
            user_profile_obj = models.UserProfile.objects.get(id=user_id)
            return render(request, 'webadmin/userprofile_modal_set_departure.html', locals())

        # 设置为在职
        elif oper_type == "set_induction":
            user_profile_obj = models.UserProfile.objects.get(id=user_id)
            return render(request, 'webadmin/userprofile_modal_set_induction.html', locals())


@pub.is_login
def client_info(request):
    name = request.session['name']

    if "type" in request.GET and request.GET.get('type') == "ajax_json":
        client_info_obj = models.ClientInfo.objects.filter(user__name=name)
        length = request.GET.get('length')  # 每页显示的数量
        start = request.GET.get('start')  # 第几页
        column_list = ['id', 'number', 'client_name', 'status', 'create_date', 'update_date', 'remark']

        data_objs = pub.combining_data(client_info_obj, request, column_list)

        line_count = data_objs.count()  # 过滤出来的数量
        data_objs = pub.paging(data_objs, start, length)  # 进行分页

        result_data = {
            'recordsFiltered': line_count,
            'data': []
        }
        for index, obj in enumerate(data_objs, start=1):

            status = ""

            for s in obj.status_choices:
                if obj.status == s[0]:
                    status = s[1]

            img = ""
            n_index = 1
            follow_records_objs = models.FollowRecords.objects.filter(client_id=obj.id)
            for f_obj in follow_records_objs:
                if f_obj.image_url:

                    for img_url in f_obj.image_url.strip('|').split('|'):
                        if img_url == "undefined":
                            continue
                        print(img_url)
                        # img += """<a href="{img_url}" target="_blank" > 截图{n_index} </a>""".format(img_url=img_url, n_index=n_index)
                        img += """<a onclick="{function}" href="{img_url}" class="popup-with-css-anim btn btn-primary btn-outline" data-effect="mfp-zoom-in"> 截图{n_index} </a>""".format(
                            img_url=img_url,
                            n_index=n_index,
                            function="aClick(event)"
                        )
                        n_index += 1

            data = {
                'number': index,
                'client_name': obj.client_name,
                'phone': obj.phone,
                'status': status,
                'img': img,
                'id': obj.id,
                'create_date': obj.create_date.strftime('%Y-%m-%d %H:%M:%S'),
                'update_date': obj.update_date.strftime('%Y-%m-%d %H:%M:%S'),
                'remark': obj.remark
            }
            result_data['data'].append(data)
        return JsonResponse(result_data)

    if "_pjax" in request.GET:
        return render(request, 'webadmin/client_info_pjax.html', locals())
    return render(request, 'webadmin/client_info.html', locals())


@pub.is_login
def client_info_oper(request, oper_type, client_id):
    response = pub.BaseResponse()

    if request.method == "POST":
        if oper_type == "create":
            form_obj = clientinfoForms(request.POST)
            if form_obj.is_valid():
                models.ClientInfo.objects.create(
                    client_name=form_obj.cleaned_data['client_name'],
                    contact_name=form_obj.cleaned_data['contact_name'],
                    phone=form_obj.cleaned_data['phone'],
                    qq=form_obj.cleaned_data['qq'],
                    status=form_obj.cleaned_data['status'],
                    remark=form_obj.cleaned_data['remark'],
                    user=models.UserProfile.objects.get(name=request.session['name']),
                )
                response.status = True
                response.message = "客户 {client_name} 添加成功!".format(client_name=form_obj.cleaned_data['client_name'])

            else:
                response.status = False
                response.message = form_obj.errors[list(form_obj.errors.keys())[0]]

        elif oper_type == "update":
            form_obj = clientinfoForms_update(request.POST)
            if form_obj.is_valid():
                client_info_obj = models.ClientInfo.objects.get(id=form_obj.cleaned_data['id'])

                client_info_obj.client_name=form_obj.cleaned_data['client_name']
                client_info_obj.contact_name=form_obj.cleaned_data['contact_name']
                client_info_obj.phone=form_obj.cleaned_data['phone']
                client_info_obj.qq=form_obj.cleaned_data['qq']
                client_info_obj.status=form_obj.cleaned_data['status']
                client_info_obj.remark=form_obj.cleaned_data['remark']
                client_info_obj.save()

                response.status = True
                response.message = "客户 {name} 修改成功!".format(name=form_obj.cleaned_data['client_name'])

            else:
                response.status = False
                response.message = form_obj.errors[list(form_obj.errors.keys())[0]]
        return JsonResponse(response.__dict__)
    else:
        if oper_type == "create":
            status_choices = models.ClientInfo.status_choices
            return render(request, 'webadmin/client_info_modal_create.html', locals())

        elif oper_type == "select":
            client_info_obj = models.ClientInfo.objects.get(id=client_id)
            return render(request, 'webadmin/client_info_modal_select.html', locals())

        elif oper_type == "update":
            client_info_obj = models.ClientInfo.objects.get(id=client_id)
            return render(request, 'webadmin/client_info_modal_update.html', locals())


@pub.is_login
def client_all_info(request):
    name = request.session['name']
    user_id = request.session['user_id']

    user_profile_obj = models.UserProfile.objects.get(id=user_id)
    department = user_profile_obj.department

    if "type" in request.GET and request.GET.get('type') == "ajax_json":

        if not department:
            client_info_obj = models.ClientInfo.objects.all()
        else:
            client_info_obj = models.ClientInfo.objects.filter(user__department_id=department.id)
        print(request.GET)
        if "department_name" in request.GET and request.GET.get('department_name'):
            department_name = request.GET.get('department_name')
            print(department_name)
            client_info_obj = client_info_obj.filter(user__department__name=department_name)

        if "user_name" in request.GET and request.GET.get('user_name'):
            user_name = request.GET.get('user_name')
            client_info_obj = client_info_obj.filter(user__name__contains=user_name)

        if "create_date" in request.GET and request.GET.get('create_date'):
            create_date = request.GET.get('create_date')
            client_info_obj = client_info_obj.filter(create_date__contains=create_date)

        if "update_date" in request.GET and request.GET.get('update_date'):
            update_date = request.GET.get('update_date')
            client_info_obj = client_info_obj.filter(update_date__contains=update_date)

        length = request.GET.get('length')  # 每页显示的数量
        start = request.GET.get('start')  # 第几页
        column_list = ['id', 'number', 'user__name', 'user__department__name', 'client_name', 'status', 'create_date', 'update_date', 'remark']

        data_objs = pub.combining_data(client_info_obj, request, column_list)

        line_count = data_objs.count()  # 过滤出来的数量
        data_objs = pub.paging(data_objs, start, length)  # 进行分页

        result_data = {
            'recordsFiltered': line_count,
            'data': []
        }
        for index, obj in enumerate(data_objs, start=1):

            status = ""

            for s in obj.status_choices:
                if obj.status == s[0]:
                    status = s[1]

            if obj.user.department:
                department_name = obj.user.department.name
            else:
                department_name = None

            if user_profile_obj.name == "董庆豪":
                client_name = ""
            else:
                client_name = obj.client_name

            img = ""
            n_index = 1
            follow_records_objs = models.FollowRecords.objects.filter(client_id=obj.id)
            for f_obj in follow_records_objs:
                if f_obj.image_url:

                    for img_url in f_obj.image_url.strip('|').split('|'):

                        # img += """<a href="{img_url}" target="_blank" > 截图{n_index} </a>""".format(img_url=img_url, n_index=n_index)
                        img += """<a onclick="{function}" href="{img_url}" class="popup-with-css-anim btn btn-primary btn-outline" data-effect="mfp-zoom-in"> 截图{n_index} </a>""".format(
                            img_url=img_url,
                            n_index=n_index,
                            function="aClick(event)"
                        )
                        n_index +=1

            data = {
                'number': index,
                'client_name': client_name,
                'user_name': obj.user.name,
                'department_name': department_name,
                'phone': obj.phone,
                'status': status,
                'img': img,
                'id': obj.id,
                'create_date': obj.create_date.strftime('%Y-%m-%d %H:%M:%S'),
                'update_date': obj.update_date.strftime('%Y-%m-%d %H:%M:%S'),
                'remark': obj.remark
            }
            print(data)
            result_data['data'].append(data)
        return JsonResponse(result_data)

    department_obj = models.Department.objects.all()
    if "_pjax" in request.GET:
        return render(request, 'webadmin/client_all_info_pjax.html', locals())
    return render(request, 'webadmin/client_all_info.html', locals())


@pub.is_login
def client_all_info_oper(request, oper_type, client_id):
    response = pub.BaseResponse()

    if oper_type == "select":
        client_info_obj = models.ClientInfo.objects.get(id=client_id)
        return render(request, 'webadmin/client_all_info_modal_select.html', locals())


@pub.is_login
def follow_records_oper(request, oper_type, o_id):
    response = pub.BaseResponse()

    if request.method == "POST":
        if oper_type == "create":

            img_urls = request.POST.get('img_urls')
            content = request.POST.get('content')
            client_id = request.POST.get('client_id')

            models.FollowRecords.objects.create(
                client_id = client_id,
                content=content,
                image_url=img_urls,
            )

            response.status = True
            response.message = "跟进记录添加成功"

        elif oper_type == "update":
            print(request.POST)
            img_urls = request.POST.get('img_urls')
            content = request.POST.get('content')

            follow_records_obj = models.FollowRecords.objects.get(id=o_id)
            follow_records_obj.content = content
            follow_records_obj.image_url = img_urls
            follow_records_obj.save()

            response.status = True
            response.message = "跟进记录修改成功"
        return JsonResponse(response.__dict__)
    else:
        if oper_type == "create":
            return render(request, 'webadmin/follow_records_modal_create.html', locals())

        elif oper_type == "select":
            client_info_obj = models.ClientInfo.objects.get(id=o_id)
            follow_records_obj = models.FollowRecords.objects.filter(client=client_info_obj)

            return render(request, 'webadmin/follow_records_modal_select.html', locals())

        elif oper_type == "update":
            follow_records_obj = models.FollowRecords.objects.get(id=o_id)
            if follow_records_obj.image_url:
                img_list = follow_records_obj.image_url.strip('|').split('|')
            return render(request, 'webadmin/follow_records_modal_update.html', locals())


@pub.is_login
def follow_records_all_oper(request, oper_type, o_id):
    response = pub.BaseResponse()

    if oper_type == "select":
        client_info_obj = models.ClientInfo.objects.get(id=o_id)
        follow_records_obj = models.FollowRecords.objects.filter(client=client_info_obj)

        return render(request, 'webadmin/follow_records_all_modal_select.html', locals())


@pub.is_login
def zuoduihua(request):
    name = request.session['name']
    user_id = request.session['user_id']

    if "type" in request.GET and request.GET.get('type') == "ajax_json":
        department = models.UserProfile.objects.get(id=user_id).department
        if not department:
            duiua_obj = models.DuiHua.objects.all()
        else:
            duiua_obj = models.DuiHua.objects.filter(user__department_id=department.id)

        length = request.GET.get('length')  # 每页显示的数量
        start = request.GET.get('start')  # 第几页
        column_list = ['number', 'keyworld', 'create_date', 'user__name', 'user__department__name', 'remark', 'settings']

        data_objs = pub.combining_data(duiua_obj, request, column_list)

        line_count = data_objs.count()  # 过滤出来的数量
        data_objs = pub.paging(data_objs, start, length)  # 进行分页

        result_data = {
            'recordsFiltered': line_count,
            'data': []
        }
        for index, obj in enumerate(data_objs, start=1):

            if obj.user.name == name:
                settings = '<i class="fa fa-edit" href="update/{id}/" data-toggle="modal" data-target="#modal"></i>' \
                           '<i class="fa fa-trash-o" href="delete/{id}/" data-toggle="modal" data-target="#modal" style="margin-left: 10px"></i>'.format(
                    id=obj.id
                )
            else:
                settings = ''

            if obj.user.department:
                department_name = obj.user.department.name
            else:
                department_name = None

            data = {
                'number': index,
                'keyworld': "<a href='{url}' target='_blank'>{keyworld}</a>".format(url=obj.link, keyworld=obj.keyworld),
                'create_date': obj.create_date.strftime('%Y-%m-%d %H:%M:%S'),
                'user': obj.user.name,
                'department_name': department_name,
                'remark': obj.remark,
                'settings': settings
            }
            result_data['data'].append(data)
        return JsonResponse(result_data)

    if "_pjax" in request.GET:
        return render(request, 'webadmin/zuoduihua_pjax.html', locals())
    return render(request, 'webadmin/zuoduihua.html', locals())


@pub.is_login
def zuoduihua_oper(request, oper_type, o_id):
    name = request.session['name']
    response = pub.BaseResponse()

    if request.method == "POST":
        if oper_type == "create":
            models.DuiHua.objects.create(
                user=models.UserProfile.objects.get(name=name),
                keyworld=request.POST.get('keyworld'),
                link=request.POST.get('link'),
                remark=request.POST.get('remark'),
            )

            response.status = True
            response.message = "添加成功!"

        elif oper_type == "update":
            duihua_obj = models.DuiHua.objects.get(id=o_id)
            duihua_obj.keyworld = request.POST.get('keyworld')
            duihua_obj.link = request.POST.get('link')
            duihua_obj.remark = request.POST.get('remark')
            duihua_obj.save()

            response.status = True
            response.message = "修改成功!"

        elif oper_type == "delete":
            duihua_obj = models.DuiHua.objects.get(id=o_id).delete()
            response.status = True
            response.message = "删除成功!"

        return JsonResponse(response.__dict__)
    else:
        if oper_type == "create":
            return render(request, 'webadmin/zuoduihua_modal_create.html', locals())

        elif oper_type == "delete":
            duihua_obj = models.DuiHua.objects.get(id=o_id)

            return render(request, 'webadmin/zuoduihua_modal_delete.html', locals())

        elif oper_type == "update":
            duihua_obj = models.DuiHua.objects.get(id=o_id)
            return render(request, 'webadmin/zuoduihua_modal_update.html', locals())

